/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.toolkit.impl;

import java.math.BigDecimal;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import who.tmap.bo.AttrDef;
import who.tmap.bo.Attrs;
import who.tmap.bo.ThematicMap;
import who.tmap.bo.impl.BizObjectFactory;
import who.tmap.common.TMapException;
import who.tmap.dao.TMapDAOException;

/**
 * @author stl
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class AttrHelper {
	
    private static Logger logger = Logger.getLogger(AttrHelper.class);	
	
    public static final String CD_POINT_X_COLUMN ="X";
    public static final String CD_POINT_Y_COLUMN ="Y";  
    public static final String CD_POINT_DESC_COLUMN ="Desc";  
    public static final String CD_POINT_SIZE_COLUMN ="Size";   	

    /**
     * Find another (more elegant) way to do this later
     * we get an exception from getColumnClass( ct ).newInstance();
     * need to pass a parameter when instanciating
     * @param strValue
     * @param attrType
     * @return
     * @throws TMapDAOException
     */
    public Object getNewInstanceFromClassName( String attrType ) throws TMapException {
        Object value =null;
        
        try {      
            if ( BigDecimal.class.getName().equals( attrType ) ) {
                value =new BigDecimal(0);
            } else if ( Boolean.class.getName().equals( attrType ) ) {
                value =new Boolean(false);
            } else if ( Byte.class.getName().equals( attrType ) ) {
                value =new Byte((byte) 0);
            } else if ( Short.class.getName().equals( attrType ) ) {
                value =new Short((short) 0);
            } else if ( Integer.class.getName().equals( attrType ) ) {
                value =new Integer(0);
            } else if ( Long.class.getName().equals( attrType ) ) {
                value =new Long(0);
            } else if ( Float.class.getName().equals( attrType ) ) {
                value =new Float(0);
            } else if ( Double.class.getName().equals( attrType ) ) {
                value =new Double(0);
            } else if ( String.class.getName().equals( attrType ) ) {
                value =new String( "" );
            } else {
                throw new TMapException( "Invalid class name: [" + attrType + "]" );
            }
            
        } catch( Exception e ) {
            e.printStackTrace();
            value =new String();
        }
        
        return value;
    }   
    
    /**
     * Returns a "0" String if the String is empty
     * @param strValue
     * @return
     */
    private String getValidNumericString( String strValue ) {
        return ( ( strValue == null ) || ( strValue.equals( "" ) ) ) ? "0" : strValue;
    }    
    
    /**
     * Instanciate a new object and assign a value to it
     * Find a more elegant way later
     * @param strValue
     * @param attrType
     * @return
     * @throws TMapDAOException
     */
    public Object getValueFromString( String strValue, String attrType ) {
        Object value =null;
             
        if ( BigDecimal.class.getName().equals( attrType ) ) {
            value =new BigDecimal( getValidNumericString( strValue ) );
        } else if ( Boolean.class.getName().equals( attrType ) ) {
            value =new Boolean( strValue );
        } else if ( Byte.class.getName().equals( attrType ) ) {
            value =new Byte( getValidNumericString( strValue ) );
        } else if ( Short.class.getName().equals( attrType ) ) {
            value =new Short( getValidNumericString( strValue ) );
        } else if ( Integer.class.getName().equals( attrType ) ) {
            value =new Integer( getValidNumericString( strValue ) );
        } else if ( Long.class.getName().equals( attrType ) ) {
            value =new Long( getValidNumericString( strValue ) );
        } else if ( Float.class.getName().equals( attrType ) ) {
            value =new Float( getValidNumericString( strValue ) );
        } else if ( Double.class.getName().equals( attrType ) ) {
            value =new Double( getValidNumericString( strValue ) );
        } else if ( String.class.getName().equals( attrType ) ) {
            value =new String( strValue );
        } else {
            value =new String( strValue );
        }
        
        return value;
    }    
    
    /**
     * Convert a jdbc type into a java class name (Boolean, Double, String)
     * @param cell
     * @return the java class name
     */
    public String getType( short jdbcType ) {
        String type;
        
        switch( jdbcType ) {
        	case Types.NUMERIC:
        	case Types.DECIMAL:
        	    type =BigDecimal.class.getName();
        		break;
        		
            case Types.BIT:
            case Types.BOOLEAN:
                type =Boolean.class.getName();
            	break;
            	
            case Types.TINYINT:
                type =Byte.class.getName();
            	break;
            	
            case Types.SMALLINT:
                type =Short.class.getName();
                break;
            
            case Types.INTEGER:
                type =Integer.class.getName();
            	break;
            	
            case Types.BIGINT:
                type =Long.class.getName();
            	break;
            	
            case Types.REAL:
                type =Float.class.getName();
            	break;
            	
            case Types.FLOAT:
            case Types.DOUBLE:
            	type =Double.class.getName();
            	break;
        
        	case Types.CHAR:
        	case Types.VARCHAR:
        	case Types.LONGVARCHAR:
	    	default:
	    	    type =String.class.getName();	
        }
        
        return type;        
    }	    
    
    /**
     * Gets the index rank for an attribute name
     * @param headers
     * @param attrName
     * @return
     * @throws TMapException
     */
    public int getIdxForAttrName( List<AttrDef> headers, String attrName ) throws TMapException {
		int colIdx =-1;
		
		for( int ct =0; ct < headers.size(); ct++ ) {
			AttrDef attrDef =(AttrDef)headers.get( ct );
			
			if ( attrName.equalsIgnoreCase( attrDef.getName() ) ) {
				colIdx =ct;
				break;
			}
		}
		
		if ( colIdx == -1 ) {
			throw new TMapException( "Cannot find attributes column [" + attrName + "]" );
		}

		return colIdx;
    }
    
	@SuppressWarnings("unchecked")
	public void buildStructureForPointEntry( ThematicMap thematicMap ) {
		Attrs data =thematicMap.getData();
		
		try {
			if ( data == null ) {
				data =(Attrs)BizObjectFactory.getInstance().get( BizObjectFactory.ATTRS );
				thematicMap.setData( data );
			}
			
			List<AttrDef> header =data.getHeader();
			if ( header == null ) {
				header =new ArrayList<AttrDef>();
				data.setHeader( header );
			} else {
				header.clear();
			}
			
			header.add( buildAttrDef( CD_POINT_X_COLUMN, Double.class.getName() ) );
			header.add( buildAttrDef( CD_POINT_Y_COLUMN, Double.class.getName() ) );
			header.add( buildAttrDef( CD_POINT_DESC_COLUMN, String.class.getName() ) );
			header.add( buildAttrDef( CD_POINT_SIZE_COLUMN, Integer.class.getName() ) );	
			
			List<List> rows =data.getRows();
			if ( rows == null ) {
				rows =new ArrayList<List>();
				data.setRows( rows );
			} else {
				rows.clear();
			}
			
//			data.setXColumnIdx( 0 );
//			data.setYColumnIdx( 1 );
//			data.setDescriptorColumnIdx( 2 );

		} catch (TMapException e) {
			logger.error( e );
		}
		
	}
	
	private AttrDef buildAttrDef( String name, String type ) throws TMapException {
        AttrDef attrDef =(AttrDef)BizObjectFactory.getInstance().get( BizObjectFactory.ATTR_DEF );
        
        attrDef.setName( name );
        attrDef.setType( type );
        
        return attrDef;
	}    
    
}
